<template>
  <div class="writer-wraper">
    <Toast v-if="showloading" :message="$lang.loading"></Toast>
    <div class="top-bar">
      <span class="cancel" @click="openCancelAction()">{{ $lang.cancel }}</span>

      <span class="title">{{ titleMap[writeType] }}</span>
      <span
        :class="submitActive ? 'submitActive' : 'submit'"
        @click="beforeSendCheck"
        >{{ $lang.send }}</span
      >
    </div>

    <!-- <van-popup v-model="isSending" style="padding: 10px">
      <van-loading size="24px" v-show="isSending">{{
        $lang.sending
      }}</van-loading>
    </van-popup> -->

    <div
      class="filed-person"
      v-show="showRecpientsIndex == 0 || !showInputState"
      :style="inputDIVSearchStyle('toRecipients')"
    >
      <div class="title">{{ $lang.receiver }}{{ $lang.symbelColon }}</div>
      <div class="person" id="toRecipients"  @click.self="focusInputContainer('inputToRecipients')">
        <van-tag
          color="#F2F3F5"
          text-color="#646566"
          size="large"
          v-for="(p, index) in toRecipientsPeople"
          :key="p.address"
          :class="
            toRecipientsDelStatus && index == toRecipientsPeople.length - 1
              ? 'cssDel'
              : ''
          "
          @click="delPerson('toRecipients', p, index)"
        >
          {{ p.name || p.address }}
        </van-tag>

        <!-- <van-popover v-model="showPopoverTo" placement="bottom">
          <van-button type="default" @click="lostBlur('toRecipients')">
            {{ mailTmpValue.toRecipients }}
          </van-button>
          <template #reference> -->
        <input
          v-model="mailTmpValue.toRecipients"
          id="cusInputToRecipients"
          ref="inputToRecipients"
          @focus="focusInputPlace('toRecipients')"
          @compositionstart="
            keyboardState = false;
            toRecipientsDelStatus = false;
          "
          @compositionend="keyboardState = true"
          class="add-input"
          @keydown="keydownEvent"
          eventParse="toRecipients"
          autocomplete="off"
        />
        <!-- </template>
        </van-popover> -->
      </div>
      <div class="addPersonIcon" @click="personPick('toRecipients')">
        <img
          :src="require('@/assets/oppo/writemail/addPerson.svg')"
        />
      </div>
    </div>
    <div
      class="searchPeopleComponent"
      :style="getMarginTop('toRecipients')"
      v-if="mailTmpValue.toRecipients.length"
    >
      <filter-people
        v-model="mailTmpValue.toRecipients"
        mailTmpKey="toRecipients"
        @setChosenEmail="setChosenEmail"
      >
      </filter-people>
    </div>

    <div
      class="filed-person"
      v-show="showRecpientsIndex == 1 || !showInputState"
      :style="inputDIVSearchStyle('ccRecipients')"
    >
      <div class="title">{{ $lang.copyer }}{{ $lang.symbelColon }}</div>
      <div class="person" id="ccRecipients" @click.self="focusInputContainer('inputCcRecipients')">
        <van-tag
          color="#F2F3F5"
          text-color="#646566"
          size="large"
          v-for="(p, index) in ccRecipientsPeople"
          :key="p.address"
          :class="
            ccRecipientsDelStatus && index == ccRecipientsPeople.length - 1
              ? 'cssDel'
              : ''
          "
          @click="delPerson('ccRecipients', p, index)"
        >
          {{ p.name || p.address }}
        </van-tag>

        <!-- <van-popover v-model="showPopoverCC" placement="bottom">
              <van-button type="default" @click="lostBlur('ccRecipients')">{{
                mailTmpValue.ccRecipients
              }}</van-button>
              <template #reference> -->
        <input
          v-model="mailTmpValue.ccRecipients"
          class="add-input"
          ref="inputCcRecipients"
          @focus="focusInputPlace('ccRecipients')"
          @compositionstart="
            keyboardState = false;
            ccRecipientsDelStatus = false;
          "
          @compositionend="keyboardState = true"
          @keydown="keydownEvent"
          eventParse="ccRecipients"
          autocomplete="off"
        />
        <!-- </template>
            </van-popover> -->
      </div>
      <div class="addPersonIcon" @click="personPick('ccRecipients')">
        <img
          :src="require('@/assets/oppo/writemail/addPerson.svg')"
        />
      </div>
    </div>
    <div
      class="searchPeopleComponent"
      :style="getMarginTop('ccRecipients')"
      v-if="mailTmpValue.ccRecipients.length"
    >
      <filter-people
        v-model="mailTmpValue.ccRecipients"
        mailTmpKey="ccRecipients"
        @setChosenEmail="setChosenEmail"
      >
      </filter-people>
    </div>

    <div
      class="filed-person"
      v-show="showRecpientsIndex == 2 || !showInputState"
      :style="inputDIVSearchStyle('bccRecipients')"
    >
      <div class="title">{{ $lang.privatelySend }}{{ $lang.symbelColon }}</div>
      <div class="person" id="bccRecipients" @click.self="focusInputContainer('inputBccRecipients')">
        <van-tag
          color="#F2F3F5"
          text-color="#646566"
          size="large"
          v-for="(p, index) in bccRecipientsPeople"
          :key="p.address"
          :class="
            bccRecipientsDelStatus && index == bccRecipientsPeople.length - 1
              ? 'cssDel'
              : ''
          "
          @click="delPerson('bccRecipients', p, index)"
        >
          {{ p.name || p.address }}
        </van-tag>

        <!-- <van-popover v-model="showPopoverBCC" placement="bottom">
              <van-button type="default" @click="lostBlur('bccRecipients')">{{
                mailTmpValue.bccRecipients
              }}</van-button>
              <template #reference> -->
        <input
          v-model="mailTmpValue.bccRecipients"
          class="add-input"
          ref="inputBccRecipients"
          @focus="focusInputPlace('bccRecipients')"
          @compositionstart="
            keyboardState = false;
            bccRecipientsDelStatus = false;
          "
          @compositionend="keyboardState = true"
          @keydown="keydownEvent"
          eventParse="bccRecipients"
          autocomplete="off"
        />
        <!-- </template>
            </van-popover> -->
      </div>
      <div class="addPersonIcon" @click="personPick('bccRecipients')">
        <img
          :src="require('@/assets/oppo/writemail/addPerson.svg')"
        />
      </div>
    </div>
    <div
      class="searchPeopleComponent"
      :style="getMarginTop('bccRecipients')"
      v-if="mailTmpValue.bccRecipients.length"
    >
      <filter-people
        v-model="mailTmpValue.bccRecipients"
        mailTmpKey="bccRecipients"
        @setChosenEmail="setChosenEmail"
      >
      </filter-people>
    </div>

    <div class="filed-person" v-show="!showRecpientsIndex && !showInputState">
      <div class="title">{{ $lang.subject }}{{ $lang.symbelColon }}</div>
      <div class="person">
        <input
          v-model="sentForm.subject"
          style="width: 100%; font-size: 0.3733338636356rem"
          class="add-input"
          autocomplete="off"
        />
      </div>
      <div class="att-count" @click="openAction">
        <img :src="require('@/assets/oppo/attach.svg')"  />
        <span>{{ attachLength }}</span>
      </div>
    </div>

    <!-- <van-overlay
      :show="loading"
      style="display: flex; justify-content: center; align-items: center"
    >
      <van-loading size="24px" vertical>{{ $lang.loading }}</van-loading>
    </van-overlay> -->
    <Toast v-if="loading" :message="$lang.loading"></Toast>

    <div
      class="attach-outer-wraper"
      v-show="!showRecpientsIndex && !showInputState"
    >
      <attach-list
        v-show="attachmentsInSentForm && attachmentsInSentForm.length"
        @openChannelAction="openAction"
        ref="attachComponent"
        :messageID="sentForm.id"
        v-model="attachmentsInSentForm"
      ></attach-list>
    </div>
    <section
      id="section"
      v-show="!showRecpientsIndex && !showInputState"
      v-html="sentForm.content"
      ref="editor"
      contenteditable="true"
      class="editor"
      :placeholder="$lang.placeholderContent"
    ></section>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { AttachList } from "@/components";
import {
  isMailFormate,
  isMobile,
  getUrlParam,
  addWatermarkImg,
} from "@/utils/helper";
import { Dialog } from "vant";
import api from "@/apiHttp/http/index.js";
import FilterPeople from "@/components/filterPeople.vue";
// import Toast from "@/plugins/Toast/Toast";
import Toast from '@/plugins/Toast/Toast.vue';

export default {
  name: "WriteMail",
  components: { AttachList, FilterPeople, Toast },
  data() {
    return {
      showloading:false,//控制空页面返回时是否出现loading
      searchPeopleKey: "",
      isShowCopy: true, //之前默认false
      attachmentsInSentForm: [],
      // 发送邮件表单
      sentForm: {
        id: "", //lixiao
        content: "", //wf

        toRecipients: [],
        ccRecipients: [],
        bccRecipients: [],

        categories: [], // 邮件关联类别目前不知道是做什么的?
        subject: "",
        importance: "",
        contentType: "",
        inferenceClassification: "",
        attachments: [],

        //---以下没什么用--
        replyTos: [], // 回复人列表
        sender: {},
      },
      // 选人时，input临时存储变量
      mailTmpValue: {
        ccRecipients: "",
        bccRecipients: "",
        toRecipients: "",
      },

      // AddrSets: {
      //   toRecipients: new Set(),
      //   ccRecipients: new Set(),
      //   bccRecipients: new Set(),
      // },
      // 储存选人桥选择邮箱的数据
      // selectedPeople: {
      //   toRecipients: [],
      //   ccRecipients: [],
      //   bccRecipients: [],
      // },
      // 储存手动输入的邮箱数据
      // inputPeople: {
      //   toRecipients: [],
      //   ccRecipients: [],
      //   bccRecipients: [],
      // },

      submitActive: false,

      isSending: false,
      loading: false,

      //选人桥输入状态控制
      showRecpientsIndex: null,
      showInputState: false, //输入状态

      leftSlideCount: 0,
      toRecipientsPeople: [], //收件人van-tag的数据
      ccRecipientsPeople: [],
      bccRecipientsPeople: [],

      toRecipientsDelStatus: false,
      ccRecipientsDelStatus: false,
      bccRecipientsDelStatus: false,

      keyboardState: true, //检测拼音输入
    };
  },
  computed: {
    ...mapGetters(["mailType", "createReplyDetail"]),
    index() {
      return this.$route?.query?.index;
    },
    titleMap() {
      return {
        forward: this.$lang.forward,
        reply: this.$lang.reply,
        new: this.$lang.writeMail,
      };
    },
    messageId() {
      return this?.$route?.params?.id || "";
    },
    writeType() {
      return this?.$route?.query?.writeType || "";
    },
    ediInnerHTML() {
      return this.$refs.editor.innerHTML;
    },
    attachLength() {
      return this.attachmentsInSentForm?.length || "";
    },
    withAttach() {
      return this.$route?.query?.withAttach || "";
    },
    // toRecipientsSummary() {
    //   //inputPeople 里是手动输入的， selectedPeople里是选人桥输入的

    //   return (this.inputPeople?.toRecipients || []).concat(
    //     this.selectedPeople?.toRecipients
    //   );
    // },
    // ccRecipientsSummary() {
    //   return (this.inputPeople?.ccRecipients || []).concat(
    //     this.selectedPeople?.ccRecipients
    //   );
    // },
    // bccRecipientsSummary() {
    //   return (this.inputPeople?.bccRecipients || []).concat(
    //     this.selectedPeople?.bccRecipients
    //   );
    // },
    countPeople() {
      return (
        //SJY
        this.toRecipientsPeople.length +
        this.ccRecipientsPeople.length +
        this.bccRecipientsPeople.length
      );
    },
  },
  watch: {
    countPeople(newV) {
      if (newV > 0) {
        this.submitActive = true;
      } else {
        this.submitActive = false;
      }
    },
    "sentForm.subject": {
      handler(newV) {
        if (newV?.length > 255) {
          this.$toast.fail(this.$lang.errorSubjectMaxium);
          this.sentForm.subject = newV.substring(0, 255);
        }
      },
    },
    loading(newV) {
      if (!newV) {
        if (this.writeType == "forward" || this.writeType == "new") {
          const p = document.getElementById("cusInputToRecipients");
          p.focus();
        } else if (this.writeType == "reply") {
          // const p = this.$refs.editor;
          // p.focus();
        }
      }
    },
    "mailTmpValue.toRecipients"(newV) {
      if (newV.length > 0) {
        this.showRecpientsIndex = 0;
        this.showInputState = true;
        //SJY
        this.scrollOverKeyBoard(0);

        this.statusTurnOff();
      } else {
        this.showRecpientsIndex = null;
        this.showInputState = false;
      }
    },
    "mailTmpValue.ccRecipients"(newV) {
      if (newV.length > 0) {
        this.showRecpientsIndex = 1;
        this.showInputState = true;
        //SJY
        this.scrollOverKeyBoard(1);
        this.statusTurnOff();
      } else {
        this.showRecpientsIndex = null;
        this.showInputState = false;
      }
    },

    "mailTmpValue.bccRecipients"(newV) {
      if (newV.length > 0) {
        this.showRecpientsIndex = 2;
        this.showInputState = true;
        //SJY
        this.scrollOverKeyBoard(2);
        this.statusTurnOff();
      } else {
        this.showRecpientsIndex = null;
        this.showInputState = false;
      }
    },
  },
  methods: {
    focusInputContainer(key){
      this.$refs[key].focus();
    },
    keydownEvent(e) {
      if (!this.keyboardState) {
        console.warn("keydownEvent", this.keyboardState);
        return;
      }
      // const dom = this.$refs.inputToRecipients;
      const _this = this;
      const key = e.currentTarget.getAttribute("eventParse");
      switch (key) {
        case "toRecipients":
          _this.ccRecipientsDelStatus = false;
          _this.bccRecipientsDelStatus = false;
          break;
        case "ccRecipients":
          _this.toRecipientsDelStatus = false;
          _this.bccRecipientsDelStatus = false;
          break;
        case "bccRecipients":
          _this.ccRecipientsDelStatus = false;
          _this.toRecipientsDelStatus = false;
          break;
      }
      console.warn("keyup.detectd");
      if (this.mailTmpValue[key].length == 0) {
        if (e.key == "Backspace" && _this[key + "People"].length > 0) {
          if (_this[key + "DelStatus"]) {
            _this[key + "People"].pop();
            _this[key + "DelStatus"] = false;
          } else {
            setTimeout(function () {
              _this[key + "DelStatus"] = true;
            }, 300);
          }
        }
      }
    },
    // SJY
    statusTurnOff() {
      this.toRecipientsDelStatus = false;
      this.ccRecipientsDelStatus = false;
      this.bccRecipientsDelStatus = false;
    },
    inputDIVSearchStyle(key) {
      if (this.mailTmpValue[key].length) {
        return {
          width: "100%",
          position: "absolute",
          zIndex: "999",
          top: "44px",
        };
      } else {
        return {};
      }
    },
    getMarginTop(key) {
      const _t1 =
        document.getElementsByClassName("filed-person")[0].offsetHeight;
      const _t2 =
        document.getElementsByClassName("filed-person")[1].offsetHeight;
      const _t3 =
        document.getElementsByClassName("filed-person")[2].offsetHeight;
      switch (key) {
        case "toRecipients":
          return { paddingTop: _t1 + "px" };
        case "ccRecipients":
          return { paddingTop: _t2 + "px" };
        case "bccRecipients":
          return { paddingTop: _t3 + "px" };
      }
    },
    //手动输入校验
    setChosenEmail(key, val, name = "") {
      if (!val) {
        return;
      }
      if (!isMailFormate(val)) {
        this.$toast.fail(this.$lang.errorEmailFormat);
        this.mailTmpValue[key] = "";
        return;
      }
      // SJY
      let _state = true;
      const _p = this[key + "People"];
      for (let i = 0; i < _p.length; i++) {
        if (val == _p[i].address) {
          this.$toast.fail(this.$lang.errorEmailRepeated);
          this.mailTmpValue[key] = "";
          _state = false;
          return;
        }
      }
      if (_state) {
        _p.push({
          address: val,
          name: name.length ? name : val,
          photo: "",
        });
        this.$nextTick(() => {
          this.focusInputPlace(key);
        });
        this.mailTmpValue[key] = "";
      }
    },
    focusInputPlace(key) {
      switch (key) {
        case "toRecipients":
          this.scrollOverKeyBoard(0);
          break;
        case "ccRecipients":
          this.scrollOverKeyBoard(1);
          break;
        case "bccRecipients":
          this.scrollOverKeyBoard(2);
          break;
      }
    },
    scrollOverKeyBoard(index) {
      let top = 0;
      const t1 = this.$refs.inputToRecipients.offsetTop;
      const t2 = this.$refs.inputCcRecipients.offsetTop;
      const t3 = this.$refs.inputBccRecipients.offsetTop;
      switch (index) {
        case 0:
          top = t1 - 50;
          break;
        case 1:
          top = t1 + t2 - 150;
          break;
        case 2:
          top = t1 + t2 + t3 - 150;
          break;
      }
      window.setTimeout(() => {
        window.scrollTo({ top: top, behavior: "smooth" });
      }, 300);
    },
    popNoEmailDialog(noEmailPersonName) {
      Dialog.confirm({
        title: this.$lang.errorNoEmailAddress,
        message: `${noEmailPersonName}`,
        confirmButtonText: this.$lang.yes,
        cancelButtonText: this.$lang.no,
        className: "errSelfDialog",
      }).then(() => {});
    },
    //选人桥
    async selectPersonMethod(key) {
      //async
      try {
        let resArr = await this.SelectPerson(this[key + "People"]);
        // let resArr = {
        //   //开发本地测试数据
        //   data: {
        //     persons: [
        //       {
        //         email: "60109895464562@qq.com",
        //         name: "呼呼",
        //       },
        //       {
        //         email: "601088979498951@qq.com",
        //         name: "小屁屁",
        //       },
        //       {
        //         email: "1@qq.com",
        //         name: "测试模拟1",
        //       },
        //       {
        //         email: "2@qq.com",
        //         name: "渐渐强强",
        //       },
        //       {
        //         email: "3@qq.com",
        //         name: "喜喜",
        //       },
        //       {
        //         email: "545466464564@qq.com",
        //         name: "黄泉人",
        //       },
        //       {
        //         email: "605546541203@qq.com",
        //         name: "可爱",
        //       },
        //       {
        //         email: "654749806@qq.com",
        //         name: "都是假的",
        //       },
        //       {
        //         email: "6017@qq.com",
        //         name: "是否如此",
        //       },
        //       {
        //         email: "6018@qq.com",
        //         name: "坚贞不屈",
        //       },
        //       {
        //         email: "609@qq.com",
        //         name: "热情如火",
        //       },
        //       {
        //         email: "604469489490@qq.com",
        //         name: "三心二意",
        //       },
        //       {
        //         email: "6010266229845951@qq.com",
        //         name: "一箭双雕",
        //       },
        //       {
        //         email: "60109444811@qq.com",
        //         name: "爱爱爱爱",
        //       },
        //       {
        //         email: "601087979849812@qq.com",
        //         name: "可惜",
        //       },
        //       {
        //         email: "60109813@qq.com",
        //         name: "搞笑",
        //       },
        //       {
        //         email: "6010981445846@qq.com",
        //         name: "i科幻",
        //       },
        //       {
        //         email: ["60168749879098915@qq.com"],
        //         name: "小顶顶顶顶",
        //       },
        //       {
        //         email: ["60109895116@qq.com"],
        //         name: "大大方方",
        //       },
        //       {
        //         email: ["60109895117@qq.com"],
        //         name: "时许",
        //       },
        //     ],
        //   },
        // };
        console.warn("resArr", resArr?.data);
        let selectArr = [];
        if (resArr?.data?.persons?.length) {
          selectArr = resArr.data.persons.map((p) => {
            const r = { ...p };
            r["name"] = p?.name;
            r["address"] = p?.email ? p?.email : "";
            return r;
          });
        }
        console.warn("key, selectArr", key,selectArr);

        let noEmailPeople = [];
        for (let i = 0; i < selectArr.length; i++) {
          if (!selectArr[i]?.email || selectArr[i]?.email?.length == 0) {
            noEmailPeople.push(selectArr[i]?.name || selectArr[i]?.phone);
          } else {
            // SJY _p
            let _state = true;
            const _p = this[key + "People"];
            for (let j = 0; j < _p.length; j++) {
              if (selectArr[i].address == _p[j].address) {
                this.$toast.fail(this.$lang.errorEmailRepeated);
                this.mailTmpValue[key] = "";
                _state = false;
                break;
              }
            }
            if (_state) {
              _p.push(selectArr[i]);
            }
          }
        }

        if (noEmailPeople.length) {
          const noEmailPersonName = noEmailPeople.join(", ");
          this.popNoEmailDialog(noEmailPersonName);
        }
      } catch (e) {
        console.error("调用选人桥失败:");
        console.error(e);
      }
    },

    personPick(type) {
      switch (type) {
        case "toRecipients":
          this.selectPersonMethod("toRecipients");
          break;
        case "ccRecipients":
          this.selectPersonMethod("ccRecipients");
          break;
        case "bccRecipients":
          this.selectPersonMethod("bccRecipients");
          break;
      }
    },

    getAttachmentByte(attachmentId) {
      return `/mail-office365-exchange/attachment/getAttachmentByte?messageId=${this.sentForm?.id}&attachmentId=${attachmentId}`;
    },
    withAttachInit() {
      this.attachmentsInSentForm = this.attachmentsInSentForm?.map((f) => {
        const r = {};
        r["contentType"] = f.contentType;
        r["id"] = f.id;
        r["content"] = this.getAttachmentByte(f.id);
        r["file"] = "File";
        r["fileName"] = f.name;
        r["fileSize"] = f.size;
        r["status"] = "finished";
        return r;
      });
    },
    commonAttach() {
      this.$nextTick(() => {
        this.attachmentsInSentForm = this.sentForm.attachments;
      });
    },
    
    commonOriginalContent() {
      if (!this?.sentForm?.attachments?.length) {
        this.sentForm.attachments = [];
      }
      let contentData = this.sentForm["content"] || "";
      let draft = this.sentForm['contentDrafts'] || "";
      const index = contentData.indexOf("<hr");

      // 回复插入换行符
      draft = draft ? draft + "<br/>" : "";
      if (index > -1) {
        //返回的是富文本
        if (this.writeType !== "new" && this.writeType !== "draft") {
          
          this.sentForm["content"] = draft +
            contentData.slice(0, index) +
            "<br/><br/><br/><br/><br/><br/>" +
            contentData.slice(index);
        }
      } else {
        //是纯文本，进行一些格式的处理
        if (contentData.indexOf("From:") > -1) {
          contentData = `<br/><br/><br/><br/><br/><br/>${this.sentForm["content"]}`;
          contentData = contentData.replace(
            /(From:)|(Sent:)|(To:)|(Cc:)|(Subject:)/g,
            `<br><br><b>$1$2$3$4$5</b>`
          );
        }
        this.sentForm["content"] = draft + contentData;
        this.sentForm["contentType"] = "HTML";
      }
    },
    commonRequestBody() {
      const {
        bccRecipients,
        categories,
        ccRecipients,
        content,
        contentType,
        importance,
        inferenceClassification,
        // id,
        // replyTos,
        subject,
        toRecipients,
      } = this.sentForm;

      const requestBody = {
        bccRecipients,
        categories,
        ccRecipients,
        content,
        contentType,
        importance,
        inferenceClassification,
        // id,
        // replyTos,
        subject,
        toRecipients,
      };
      return requestBody;
    },
    beforeSendCheck() {
      this.sentForm.attachments = [...this.attachmentsInSentForm];
      this.sentForm.content = this.$refs.editor.innerHTML;

      this.personArrayHandle("toRecipients");
      this.personArrayHandle("ccRecipients");
      this.personArrayHandle("bccRecipients");

      if (!this.sentForm.toRecipients.length) {
        this.$toast.fail(this.$lang.errorReceiverNone);
        return false;
      }

      //发送人数校验:收件人/抄送人/密送人合计不能超过500个）
      if (this.countPeople > 500) {
        this.$toast.fail(this.$lang.errorPersonsMaxium);
        return false;
      }
      // 发送前的确认弹窗！
      if (!this.sentForm.subject && !this.sentForm.content) {
        Dialog.confirm({
          message: this.$lang.errorNoSubjectContent,
          confirmButtonText: this.$lang.yes,
          cancelButtonText: this.$lang.no,
          className: "errSelfDialog",
        })
          .then(() => {
            this.send();
          })
          .catch(() => {
            return false;
          });
        return;
      }
      if (!this.sentForm.subject) {
        Dialog.confirm({
          message: this.$lang.noSubjectNoti,
          confirmButtonText: this.$lang.yes,
          cancelButtonText: this.$lang.no,
          className: "errSelfDialog",
        })
          .then(() => {
            this.send();
          })
          .catch(() => {
            //on cancel
            return false;
          });
        return;
      }
      if (!this.sentForm.content) {
        Dialog.confirm({
          message: this.$lang.noContentNoti,
          confirmButtonText: this.$lang.yes,
          cancelButtonText: this.$lang.no,
          className: "errSelfDialog",
        })
          .then(() => {
            this.send();
          })
          .catch(() => {
            //on cancel
            return false;
          });
        return;
      }

      this.send();
    },

    personArrayHandle(type) {
      const peopleArr = this[type + "People"].map((p) => {
        const r = {};
        r["name"] = p.name;
        r["address"] = p.address;
        return r;
      });
      this.sentForm[type] = [...peopleArr];
    },
    back(config, delay) {
      delay = delay || 0;
      //隐藏快速回复小弹窗
      this.$store.commit("changeShowReply", false);

      if (this.writeType === "new" && config && config.emptyEmail) {
        // 新增空邮件 删除邮件
        let arr = [];
        console.warn("删除空邮件",this.sentForm.id);
        arr.push(this.sentForm.id);
        console.error(arr);
        this.showloading = true
       const fo = api.post(`/message/delMessages`, {
          ids: arr,
        }).then(res =>{
        } )
      }

      if (this.writeType === "new" || this.writeType === "draft") {
        if (isMobile() && window.qing.isSupportNativeJsBridge) {
          if(!delay){
            window.qing.call("closeWebView");
            this.showloading = false
          }else{
            setTimeout(() => {
            window.qing.call("closeWebView");
            this.showloading = false
            }, delay);
          }
          
        } else {
          this.$router.replace("/home");
          setTimeout(() => {
            this.showloading = false
          }, delay)
        }
      } else {
        //reply || forward
        this.$router.replace({
          path: `/emailDetail/${this.messageId}`,
          query: {
            index: this.index,
          },
        });
      }
    },

    // 删除添加的人员
    delPerson(key, selectedPerson, index) {
      this.statusTurnOff();
      document.getElementById(key).children[index].classList.add("cssDel");
      new this.$ActionSheet({
        options: [{ name: this.$lang.delete, value: "del" }],
        cancelText: this.$lang.cancel,
        onSelect: (item) => {
          if (item.value === "del") {
            const _p = this[key + "People"];
            for (let i = 0; i < _p.length; i++) {
              if (selectedPerson.address == _p[i].address) {
                _p.splice(i, 1);
                break;
              }
            }
          }
        },
        onClose: () => {
          document
            .getElementById(key)
            .children[index].classList.remove("cssDel");
        },
      });
    },
    // 打开操作面板
    openAction() {
      const _this = this;
      new this.$ActionSheet({
        options: [
          { name: this.$lang.photo, value: "photo", className: "lineClass" },
          { name: this.$lang.camera, value: "takePicture" },
          // { name: this.$lang.attachment, value: "file" },
        ],
        cancelText: this.$lang.cancel,
        description: this.$lang.attachNotExceed,
        onSelect: (item) => {
          switch (item.value) {
            case "photo":
              _this.$refs.attachComponent.openPhotoChannel();
              break;
            case "takePicture":
              _this.$refs.attachComponent.openCameraChannel();
              break;
            case "file":
              _this.$refs.attachComponent.openFileChannel();
              break;
          }
        },
      });
    },
    //关闭输入确认气泡  弃用
    // closePop(key) {
    //   switch (key) {
    //     case "toRecipients":
    //       this.$refs.inputToRecipients.placeholder = this.$lang.placeholderInput;
    //       this.showPopoverTo = false;
    //       break;
    //     case "ccRecipients":
    //       this.$refs.inputCcRecipients.placeholder = this.$lang.placeholderInput;
    //       this.showPopoverCC = false;
    //       break;
    //     case "bccRecipients":
    //       this.$refs.inputBccRecipients.placeholder = this.$lang.placeholderInput;
    //       this.showPopoverBCC = false;
    //       break;
    //   }
    // },

    // 手动输入邮箱后 进行数据校验  弃用
    // lostBlur(key) {
    //   if (!this.mailTmpValue[key]) {
    //     return;
    //   }
    //   if (!isMailFormate(this.mailTmpValue[key])) {
    //     this.$toast.fail(this.$lang.errorEmailFormat);
    //     this.mailTmpValue[key] = "";
    //     this.closePop(key);
    //     return;
    //   }

    //   if (this.AddrSets[key].has(this.mailTmpValue[key])) {
    //     this.$toast.fail(this.$lang.errorEmailRepeated);
    //     this.mailTmpValue[key] = "";
    //     this.closePop(key);
    //     return;
    //   } else {
    //     this.AddrSets[key].add(this.mailTmpValue[key]);
    //     this.inputPeople[key].push({
    //       address: this.mailTmpValue[key],
    //       name: this.mailTmpValue[key],
    //       photo: "",
    //     });

    //     this.mailTmpValue[key] = "";
    //   }

    //   this.closePop(key);
    // },

    beforeCancelCheck() {
      //若在此页面无任何输入，则直接返回
      this.sentForm.attachments = [...this.attachmentsInSentForm];
      this.sentForm.content = this.$refs.editor.innerHTML;
      const flag =
        //SJY
        this.toRecipientsPeople.length == 0 &&
        this.ccRecipientsPeople.length == 0 &&
        this.bccRecipientsPeople.length == 0 &&
        !this.sentForm.subject &&
        !this.sentForm.attachments.length &&
        this.sentForm.content.length == 0;
      if (flag) {
        return true;
      } else {
        return false;
      }
    },
    //----统一处理： 保存草稿   删除草稿------
    openCancelAction() {
      const flag = this.beforeCancelCheck();
      if (flag) {
        this.back({ emptyEmail: flag });
        return;
      } else {
        const _this = this;
        _this.leftSlideCount++;
        new this.$ActionSheet({
          options: [
            {
              name: this.$lang.saveAsDraft,
              value: "saveDraft",
              className: "lineClass",
            },
            { name: this.$lang.deleteDraft, value: "delDraft", color: "red" },
            // {name:this.$lang.cancel, value:'back'}
          ],
          cancelText: this.$lang.cancel,
          // cancelText: "返回",
          onSelect: (item) => {
            switch (item.value) {
              case "saveDraft":
                this.sentForm.content = this.$refs.editor.innerHTML;
                if (_this.writeType == "forward") {
                  _this.saveForwardDraft(900);
                } else if (_this.writeType == "reply") {
                  _this.saveReplyDraft(900);
                } else if (
                  _this.writeType == "new" ||
                  _this.writeType == "draft"
                ) {
                  _this.saveNewDraft(900);
                }

                break;
              case "delDraft":
                if (_this.writeType == "forward") {
                  _this.delForwardDraft(900);
                } else if (_this.writeType == "reply") {
                  _this.delReplyDraft(900);
                } else if (
                  _this.writeType == "new" ||
                  _this.writeType == "draft"
                ) {
                  _this.delNewDraft(900);
                }
                break;
            }
          },
          onCancel: () => {
            _this.leftSlideCount = 0;
          },
          onClose: () => {
            _this.leftSlideCount = 0;
          },
        });
      }
    },
    //---统一处理：  根据类型 发送（发送加延时展示提示框）---------------
    send() {
      if (this.writeType === "reply") {
        this.sendReply();
      } else if (this.writeType === "new") {
        this.sentForm.importance = "NORMAL";
        this.sentForm["inferenceClassification"] = "FOCUSED";
        this.sendWriteNew();
      } else {
        //转发
        this.sendForward();
      }
    },

    //------------------回复相关---------------------
    //创建回复时， 让收件人去重
    // AddrSetsInitInReply(key) {
    //   if (this[key+'People'].length) {
    //     for (let i = 0; i < this[key+'People'].length; i++) {
    //       this.AddrSets[key].add(this.inputPeople[key][i].address);
    //     }
    //   }
    // },

    //创建回复
    async createReply() {
      this.sentForm = { ...this.createReplyDetail };
      // const sub = this.sentForm.subject.replace(/^(RE:)/, "回复：");
      // this.sentForm.subject = sub;

      //新变量  SJY
      this.toRecipientsPeople = [...this.createReplyDetail.toRecipients];
      this.ccRecipientsPeople = [...this.createReplyDetail.ccRecipients];
      this.bccRecipientsPeople = [...this.createReplyDetail.bccRecipients];

      if (this.createReplyDetail?.ccRecipients?.length) {
        this.isShowCopy = true;
      }
      //回复一般不需要附件
      if (
        !this.sentForm?.attachments?.length ||
        this.withAttach === "withoutAttach"
      ) {
        this.sentForm.attachments = [];
      }
      this.commonOriginalContent();
      this.loading = false;
      this.$imbedapi(666001001, "creatMail").then((res) =>
        console.warn(res, "邮件创建")
      );
    },
    //发送回复
    async sendReply() {
      this.isSending = true;
      this.$toast.loading({
        message:this.$lang.sending,
        duration:0
        }
        )
      const requestBody = this.commonRequestBody();
      requestBody["id"] = this.sentForm.id;
      try {
        const res = await this.Api.sendReply(requestBody);
        const { success } = res?.data;
        if (success) {
          this.isSending = false;
          this.$toast.clear()
          this.$imbedapi(666001002, "sendMail").then((res) =>
            console.warn(res, "邮件发送")
          );
          this.$toast.success(this.$lang.succeedReply);
          this.back(false, 900);
        }
      } catch(err) {
        if(err != 600){
          this.isSending = false;
          this.$toast.clear()
        }
        console.error(err,":::::");
        // this.$toast.fail(this.$lang.errorNetwork);
        // console.error(this.$lang.errorReplt);
      }
    },
    async saveReplyDraft(delay) {
      delay = delay || 0;
      const requestBody = this.commonRequestBody();
      requestBody.toRecipients = this.toRecipientsPeople;
      requestBody.ccRecipients = this.ccRecipientsPeople;
      requestBody.bccRecipients = this.bccRecipientsPeople;
      requestBody["id"] = this.sentForm.id;
      try {
        const res = await this.Api.saveReply(requestBody);
        const { success } = res?.data;
        if (success) {
          this.$toast.success(this.$lang.successSave);
          this.back(false, delay);
        }
      } catch {
        this.$toast.fail(this.$lang.saveFail);
        console.error("保存回复草稿失败");
      }
    },
    async delReplyDraft(delay) {
      delay = delay || 0;
      let err = "";
      try {
        const res = await this.Api.delReply(this.sentForm.id);
        const { success, error } = res?.data;
        if (success) {
          this.$toast.success(this.$lang.successDelete);
          this.back(false, delay);
        } else {
          err = error;
        }
      } catch {
        this.leftSlideCount = 0
        // this.$toast.fail(this.$lang.errorNetwork);
        console.error("删除回复草稿");
      }
    },

    //------------------写邮件相关-----------------------
    async createWriteNew() {
      try {
        this.showloading = true
        const res = await this.Api.createWriteNew();
        const { success, data } = res?.data;
        if (success) {
          this.$imbedapi(666001001, "creatMail").then((res) =>
            console.warn(res, "邮件创建")
          );
          this.sentForm = { ...data };
          this.showloading = false
        }
      } catch {
        console.error("写邮件创建草稿失败");
      }
    },
    async sendWriteNew() {
      this.isSending = true;
      this.$toast.loading({
        message:this.$lang.sending,
        duration:0
        }
      )
      const requestBody = this.commonRequestBody();
      requestBody["id"] = this.sentForm.id;
      requestBody["contentType"] = "HTML";
      try {
        const res = await this.Api.sendWriteNew(requestBody);
        const { success } = res?.data;
        if (success) {
          this.isSending = false;
          this.$toast.clear()
          this.$imbedapi(666001002, "sendMail").then((res) =>
            console.warn(res, "邮件发送")
          );
          this.$toast.success(this.$lang.sentSuccess);
          this.back(false, 900);
        }
      } catch(e) {
        if(e != 600){
         this.isSending = false;
         this.$toast.clear()
        }
        // this.$toast.fail(this.$lang.errorNetwork);
        console.error("发送新邮件失败",e);
      }
    },
    async saveNewDraft(delay) {
      delay = delay || 0;
      const requestBody = this.commonRequestBody();

      //SJY
      requestBody.toRecipients = this.toRecipientsPeople;
      requestBody.ccRecipients = this.ccRecipientsPeople;
      requestBody.bccRecipients = this.bccRecipientsPeople;

      requestBody["id"] = this.sentForm.id;
      requestBody["follow"] = this.sentForm.follow || false;
      try {
        const res = await this.Api.saveNewDraft(requestBody);
        const { success } = res?.data;
        if (success) {
          this.$toast.success(this.$lang.successSave);
          this.back(false, delay);
        }
      } catch {
        this.$toast.fail(this.$lang.saveFail);
        console.error("保存新邮件草稿错误");
      }
    },
    async delNewDraft(delay) {
      delay = delay || 0;
      let arr = [];
      arr.push(this.sentForm.id);
      try {
        const res = await this.Api.batchDelete({
          ids: arr,
        });
        if(res){
          const { success } = res?.data;
          if (success) {
            this.$toast.success(this.$lang.successDelete);
            this.back(false, delay);
          }
        }
      } catch(e) {
        //装饰器的dialog中给出toast提示了
        console.warn(e,"asdsdasd");
        this.$toast.success(this.$lang.DelFail);
        this.leftSlideCount = 0
        console.error("删除新邮件草稿失败");
      }
    },

    //------------转发相关---------------
    async saveForwardDraft(delay) {
      // this.beforeSaveSetting()
      delay = delay || 0;
      try {
        const requestBody = this.commonRequestBody();
        requestBody.toRecipients = this.toRecipientsPeople;
        requestBody.ccRecipients = this.ccRecipientsPeople;
        requestBody.bccRecipients = this.bccRecipientsPeople;
        requestBody["id"] = this.sentForm.id;
        const status = this.withAttach === "withAttach";
        
        if(!status){
          requestBody["withAttachment"] = false;
          requestBody.attachments = this.sentForm.attachments || [];
        }else{
          requestBody["withAttachment"] = true;
        }
        
        const res = await this.Api.updateTransmit(requestBody);
        const { success } = res?.data;
        if (success) {
          this.$toast.success(this.$lang.successSave);
          this.back(false, delay);
        } else {
          this.$toast.fail(this.$lang.saveFail);
        }
      } catch {
        // this.$toast.fail(this.$lang.saveFail);
        console.error("保存转发草稿失败");
      }
    },
    async delForwardDraft(delay) {
      delay = delay || 0;
      try {
        const res = await this.Api.delForwardDraft(this.sentForm.id);
        const { success } = res?.data;
        if (success) {
          this.$toast.success(this.$lang.successDelete);
          this.back(false, delay);
        }
      } catch {
        this.leftSlideCount = 0
        // this.$toast.fail(this.$lang.errorNetwork);
        console.error("删除转发草稿失败");
      }
    },

    async createForward() {
      try {
        const res = await this.Api.creatTransmit(this.messageId);
        const { success } = res?.data;
        if (success) {
          this.$imbedapi(666001001, "creatMail").then((res) =>
            console.warn(res, "邮件创建")
          );
          const { data } = res?.data;
          this.sentForm = { ...data };
          // const sub = this.sentForm.subject.replace(/^(FW:)/, "转发：");
          // this.sentForm.subject = sub;
          if (
            !this.sentForm?.attachments?.length ||
            this.withAttach === "withoutAttach"
          ) {
            this.sentForm.attachments = [];
          } else {
            this.attachmentsInSentForm = this.sentForm?.attachments;
            this.withAttachInit();
          }
          this.commonOriginalContent();
          this.loading = false;
        }
      } catch {
        console.error("创建转发草稿失败");
      }
    },
    async sendForward() {
      this.isSending = true;

      const {
        bccRecipients,
        content,
        contentType,
        ccRecipients,
        id,
        subject,
        toRecipients,
      } = this.sentForm;
      const requestBody = {
        bccRecipients,
        content,
        contentType,
        ccRecipients,
        id,
        subject,
        toRecipients,
      };

      const status = this.withAttach === "withAttach";
      if(!status){
        requestBody["withAttachment"] = false;
        requestBody.attachments = this.sentForm.attachments || [];
      }else{
        requestBody["withAttachment"] = true;
      }
      
      try {
        const res = await this.Api.sendTransmit(requestBody);
        const { success } = res?.data;
        if (success) {
          this.isSending = false;
          this.$imbedapi(666001002, "sendMail").then((res) =>
            console.warn(res, "邮件发送")
          );
          this.$toast.success(this.$lang.sentSuccess);
          this.back(false, 900);
        }
      } catch {
        this.isSending = false;
        // this.$toast.fail(this.$lang.errorNetwork);
        this.$toast.error(this.$lang.ForwardFail);
      }
    },

    //--------写草稿相关-------
    async createDraft() {
      try {
        const res = await this.Api.getMailDetail(this.messageId);
        const { success, data } = res?.data;
        if (success) {
          this.$imbedapi(666001001, "creatDraft").then((res) =>
            console.warn(res, "草稿创建")
          );
          this.sentForm = data;

          //SJY
          this.toRecipientsPeople = this.sentForm?.toRecipients;
          this.ccRecipientsPeople = this.sentForm?.ccRecipients;
          this.bccRecipientsPeople = this.sentForm?.bccRecipients;

          if (
            !this.sentForm?.attachments?.length ||
            this.withAttach === "withoutAttach"
          ) {
            this.sentForm.attachments = [];
          } else {
            this.attachmentsInSentForm = this.sentForm?.attachments;
            this.withAttachInit();
          }
          this.commonOriginalContent();
          this.loading = false;
        }
      } catch {
        console.error("获取草稿箱详情失败");
      }
    },
  },
  created() {
    //刚进来 滚动置顶(做兼容处理)
    try{
      console.warn("behavior obj")
      window.scrollTo({top: 0, behavior: "instant"});
    }catch(e){
      console.warn("behavior 0,0")
      window.scrollTo(0, 0);
    } 
    console.warn("writemail created@!");
    /** 从名片入口转到写邮件 */
    const callingcardName = decodeURI(
      getUrlParam("name", window.location.href)
    );
    const callingcardEmail = decodeURI(
      getUrlParam("email", window.location.href)
    );
    if (callingcardName && callingcardEmail) {
      console.warn(
        `callingcardName: ${callingcardName}, callingcardEmail: ${callingcardEmail}`
      );

      //SJY
      this.toRecipientsPeople.push({
        name: callingcardName,
        address: callingcardEmail,
      });
    }

    if (this.messageId) {
      if (this.writeType === "reply") {
        //回复
        this.loading = true;
        this.createReply();
      } else if (this.writeType === "draft") {
        //写草稿
        this.loading = true;
        this.createDraft();
      } else {
        //转发
        this.loading = true;
        this.createForward();
      }
    } else if (this.writeType === "new") {
      //写新邮件
      this.createWriteNew();
    }

    const _this = this;
    window.qing.call("defback", {
      // 阻止 安卓 左划/home键 返回
      success: function () {
        // if (_this.leftSlideCount == 0) {
        //   //leftSlideCount 阻止用户多次左滑而弹出越来越多遮罩
        //   _this.openCancelAction();
        // }
      },
    });
    const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //判断是否是 iOS终端
    if (isIOS) {
      //JS桥提供的右滑禁用方法
      if (window.$bridge) {
        window.$bridge.callHandler(
          "takeWebRightSlide",
          JSON.stringify({ isTakeOver: "y" }),
          (res) => {
            console.log("JS桥的takeWebRightSlide方法调用结果  =》 " + JSON.stringify(res));
          }
        );
      } else {
        console.error("call takeWebRightSlide error, no bridge");
      }
    }
  },
  mounted() {
    console.warn(this.writeType,"当前type");
    // if(this.writeType == 'reply'||'forward'){
    //   //增加底部安全区域适配全面屏ios
    //   window.qing.call("setWebBottomInset", {
    //     show:false, //底部是否增加34偏移量
    //     success: function (res) {
    //       console.warn(res,"不调用适配iponeX的桥增加34偏移量");
    //     },
    //   });
    // }else{
    //    window.qing.call("setWebBottomInset", {
    //     show:true, //底部是否增加34偏移量
    //     success: function (res) {
    //       console.warn(res,"调用适配iponeX的桥增加34偏移量");
    //     },
    //   });
    // }
    addWatermarkImg("section");
  },
};
</script>
<style lang="less">
.cssDel {
  background: #00c00e !important;
  color: #fff !important;
}
</style>
<style lang="less" scoped>
.writer-wraper {
  height: 100%;
  width: 100%;

  position: relative;
  padding-top: 44px;
  background-color: #fff;
  .top-bar {
    position: fixed;
    top: 0;
    width: 100%;
    height: 44px;
    display: flex;
    align-items: center;
    padding: 0 11px;
    z-index: 999;
    background: #fff;

    .cancel {
      // width: 42px;
      font-size: 16px;
      color: #323233;
    }
    .title {
      flex: 1;
      font-size: 18px;
      color: #323233;
      text-align: center;
      font-weight: 500;
    }
    .submit {
      // width: 42px;
      opacity: 0.3;
      font-size: 16px;
      color: #00c00e;
      text-align: right;
    }

    .submitActive {
      font-size: 16px;
      color: #00c00e;
      text-align: right;
      line-height: 16px;
      font-weight: 400;
    }
  }
  .popupCell {
    text-align: center;
    font-size: 16px;
    color: #323233;
    text-align: center;
    line-height: 24px;
    font-weight: 400;
  }
  .filed-person {
    box-sizing: border-box;
    min-height: 1.4933354545424rem;
    padding: 0.533334090908rem 0.4266672727264rem;
    line-height: 0.4266672727264rem;
    color: #969799 100%;
    display: flex;
    border-bottom: 1px solid #f2f3f5;
    position: relative;
    background: #fff;
    .title {
      font-size: 0.4266672727264rem;
      color: #969799;
      text-align: left;
      font-weight: 400;
      display: flex;
      align-items: flex-start;
      line-height: 0.6400009090896rem;
      padding-top: 0.1066668181816rem;
      min-width: 1.2800018181792rem;
    }
    .person {
      display: flex;
      flex-wrap: wrap;
      flex: 1;
      word-break: break-all;
      padding-right: 4px;
      overflow: hidden;
      /deep/ .van-tag {
        margin: 0.0533334090908rem 0.1066668181816rem;
        line-height: 0.4266672727264rem;
      }
      .van-popover__wrapper {
        flex: 1;
      }
      // .popover-style{
      //   padding: 3px 5px;
      //   font-size: 14px;
      // }
      .add-input {
        height: 0.6400009090896rem;
        font-size: 0.3733338636356rem;
        padding: 0 6px;
        margin: 0.1066668181816rem 0;
        width: 25%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .att-count {
      display: flex;
      align-items: center;
      color: #969799;
      min-width: 60px;
      justify-content: flex-end;
      img{
        pointer-events: none;
        width:0.4266672727264rem;
        height:0.4266672727264rem;
      }
      span{
        font-size:0.3200004545448rem;
      }
    }
    .addPersonIcon {
      margin-right: 0.133333522727rem;
      min-width: 0.533334090908rem;
      background: #fff;
      align-self: center;
      img{
        pointer-events: none;
      }
    }
    .right-option {
      font-size: 14px;
      line-height: 32px;
      color: #646566;
      min-width: 56px;
    }
  }

  .attach-outer-wraper {
    background: #fff;
    .attach-wraper {
      padding: 8px 16px 8px 16px;
    }
  }
  .editor {
    position: relative; // fixed: 需要显示在水印上面
    min-height: calc(100% - 3.0400043181756rem);
    width: 100%;
    padding: 0.4266672727264rem 0.4266672727264rem 0 0.4266672727264rem;
    outline: none;
    border: none;
    // overflow-y: auto;
    font-size: 0.4266672727264rem;
    line-height: 0.533334090908rem;
    background-color: #fff;
    &:empty:before {
      content: attr(placeholder);
      color: #bbb;
      font-size: 0.4266672727264rem;
    }
    &:focus:before {
      content: none;
    }
  }

  .searchPeopleComponent {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}
</style>
